package com.foodchain.service;


import com.foodchain.consts.Consts;
import com.foodchain.entity.Activity;
import com.foodchain.entity.ActivityContent;
import com.foodchain.repository.ActivityContentRepository;
import com.foodchain.repository.ActivityRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.List;


/**
 * @ClassName ActivityService
 * @Description TODO
 * @Author duyuanyuan
 * @Date 2019/3/13 11:04
 * @Version 1.0
 **/
@Service
public class ActivityService {

    @Resource
    private ActivityRepository activityRepository;

    @Resource
    private ActivityContentRepository contentRepository;

    public Page<Activity> findListAll(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        Specification<Activity> spec = new Specification<Activity>() {        //查询条件构造
            public Predicate toPredicate(Root<Activity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Boolean>  activityStatus= root.get("activityStatus");
                Predicate p1 = cb.isTrue(activityStatus);
                Predicate p = cb.and(p1);
                return p;
            }
        };
        Page<Activity> all = activityRepository.findAll(spec, pageable);
        if(all.getContent().size()>0) {
            for (Activity a : all) {
                a.setActivityImg(Consts.FileUrl.file_url+"/"+ a.getActivityImg());
            }
        }

        return  all;
    }

    public List<Activity> findUserListAll(String userId) {
        return activityRepository.findUserListAll(userId);
    }

    public Activity getContent(String activityId) {
        ActivityContent content = contentRepository.findByActivityId(activityId);
        Activity activity = activityRepository.getOne(activityId);
        activity.setContent(content.getContent());
        activity.setActivityImg(Consts.FileUrl.file_url+"/"+activity.getActivityImg());
        return activity;
    }

    public List<Activity> findActIng() {
        return activityRepository.findActIng();
    }

    public List<Activity> findActEnd() {
        return activityRepository.findActEnd();
    }

    public List<Activity> findActSign() {
        return activityRepository.findActSign();
    }

    public void updateStatus(Activity activity) {
        activityRepository.saveAndFlush(activity);
    }
}
